package tp.pr5.console;

import java.util.Scanner;

import tp.pr5.Constants;
import tp.pr5.Controller;
import tp.pr5.Interpreter;
import tp.pr5.RobotEngine;
import tp.pr5.instructions.Instruction;
import tp.pr5.instructions.exceptions.WrongInstructionFormatException;

public class ConsoleController extends Controller
{
	
	/**
	 * Constructor of the controller. It receives the model main class.
	 * 
	 * @param game - Game that is being played.
	 */
	public ConsoleController(RobotEngine game)
	{
		super(game);
	}
	
	/**
	 * This function implements the main loop of the simulation. Basically, it reads a line, the interpreter generates the corresponding instruction and executes it. 
	 * The simulation finishes when the robot arrives at the space ship, the user types "QUIT", or the robot runs out of fuel If the input string has a wrong format, 
	 * this method will request the robot engine to notify that an error has ocurred This method must be called once.
	 * 
	 */
	public void startController() 
	{
		game.requestStart();
		
		Instruction instruction;
		Scanner sc = new Scanner(System.in);
		
		do
		{
			System.out.print(Constants.PROMPT);
			//If the robot does not understand a command, it will throw an exception
			try
			{
				instruction = Interpreter.generateInstruction(sc.nextLine());
				this.game.communicateRobot(instruction);
				
			} catch (WrongInstructionFormatException e){
				System.out.println(Constants.MESSAGE_WHAT + Constants.LINE_SEPARATOR);
			}
		} while(!this.game.isOver());
		//If the robot receives a quit instruction, its fuel is under 0 or it has reached spaceship then, the simulation ends.
		sc.close();
	}

}
